package com.cordershy.service;

import com.cordershy.mapper.goalMapper;
import com.cordershy.pojo.goal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

@Service
public class goalService {
    @Autowired
    goalMapper goalMapper;
    @Transactional
    public List<goal> selectAll(String username){
        List<goal> goals = goalMapper.selectAll(username);
        Collections.reverse(goals);
        return goals;
    }
    @Transactional(propagation = Propagation.REQUIRED)
    @Cacheable(value = "accountCache",key = "'goalid'+#goalid")
    public goal selectById(int goalid){
        return goalMapper.selectById(goalid);
    }
    @Transactional(propagation = Propagation.REQUIRED)
    @CacheEvict(value = "accountCache",key = "'goalid'+#goalid")
    public int delete(int goalid){
        return goalMapper.delete(goalid);
    }
    @Transactional(propagation = Propagation.REQUIRED)
    @CachePut(value = "accountCache",key = "'goalid'+#goal.goalid")
    public goal insert(goal goal){
        goalMapper.insert(goal);
        return goal;
    }
    @Transactional(propagation = Propagation.REQUIRED)
    @CachePut(value = "accountCache",key = "'goalid'+#goal.goalid")
    public goal update(goal goal){
        goal temp = selectById(goal.getGoalid());
        if (temp!=null){
            goalMapper.update(goal);
        }else{
            return null;
        }
        return goal;
    }
}
